/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#ifndef AUDIO_THREAD_TASK_H
#define AUDIO_THREAD_TASK_H

#include <atomic>
#include <thread>
#include <functional>
#include <condition_variable>
#include <memory>
#include <mutex>
#include "nocopyable.h"
namespace OHOS {
namespace AudioStandard {
class __attribute__((visibility("default"))) AudioThreadTask : public NoCopyable {
public:
    explicit AudioThreadTask(const std::string &name);
    ~AudioThreadTask();
    void Start();
    void Stop();
    void StopAsync();
    void Pause();
    void PauseAsync();

    bool CheckThreadIsRunning() const noexcept;

    void RegisterJob(std::function<void()> &&job);

private:
    void doEmptyJob();
    void RunJob();

private:
    enum class RunningState {
        STARTED,
        PAUSING,
        PAUSED,
        STOPPING,
        STOPPED,
    };
    const std::string name_;
    std::atomic<RunningState> state_;
    std::mutex stateMutex_;
    std::condition_variable cond_;
    std::unique_ptr<std::thread> loop_;
    std::function<void()> job_ = [this] { doEmptyJob(); };
};
} // namespace AudioStandard
} // namespace OHOS
#endif
